package cn.migu.music.hangupsms.cachemanage.handler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import cn.migu.music.common.utils.LogUtils;
import cn.migu.music.hangupsms.cachemanage.event.AbsCacheEvent;
import cn.migu.music.hangupsms.cachemanage.event.EventConstants;
import cn.migu.music.hangupsms.common.config.HangUpSmsDbConfig;
import cn.migu.music.hangupsms.common.entity.SmsSendTimeSettings;
import cn.migu.music.hangupsms.common.entity.TimeLimit;
import cn.migu.music.hangupsms.repository.SmsSendTimeSettingsMapper;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@EqualsAndHashCode(callSuper = true)
public class SmsSendTimeCacheHandler extends AbsCacheHandler<AbsCacheEvent> {
    @Autowired
    private SmsSendTimeSettingsMapper smsSendTimeSettingsMapper;
    @Autowired
    private HangUpSmsDbConfig         hangUpSmsDbConfig;

    @PostConstruct
    @Override
    public void init() {
        reload(EventConstants.SMS_SEND_TIME_CHANGED_EVENT);
    }

    @Override
    public void reload(AbsCacheEvent cacheEvent) {
        List<SmsSendTimeSettings> timeSettingsList = null;
        try {
            timeSettingsList = smsSendTimeSettingsMapper.getAllSettings();
        } catch (Exception e) {
            LogUtils.error(e, log, "get data error");
        }
        if (CollectionUtils.isEmpty(timeSettingsList)) {
            return;
        }
        Map<String, TimeLimit> provinceTimeLimitMap = new HashMap<>();
        for (SmsSendTimeSettings settings : timeSettingsList) {
            if (settings.getApplyStatus() == null || settings.getApplyStatus() == 0) {
                continue;
            }
            TimeLimit timeLimit = new TimeLimit();
            timeLimit.setLimitNum(settings.getElapsedMaxTime());
            timeLimit.setStartTimeOfDay(settings.getDayStartTime());
            timeLimit.setEndTimeOfDay(settings.getDayEndTime());
            provinceTimeLimitMap.put(settings.getProvinceId(), timeLimit);
        }
        hangUpSmsDbConfig.setProvinceTimeLimitMap(provinceTimeLimitMap);
    }
}
